<template>
  <van-form @submit="onSubmit">
    <van-cell-group inset>
      <van-field
        v-model="username"
        name="用户名(选填)"
        label="用户名(选填)"
        placeholder="用户名"
      />
      <van-uploader
        name="头像(选填)"
        v-model="fileList"
        max-count="1"
        max-size="1024 * 1024"
        accept="image/*"
        :after-read="afterRead"
        @delete="afterDelete"
      />
      <van-cell
        title="用户名就是登录账号，更改一次信息消耗10积分(>_<)!!!"
      ></van-cell>
    </van-cell-group>
    <div style="margin: 16px">
      <van-button
        round
        block
        type="primary"
        color="linear-gradient(to right, #a9a9a9, #333333)"
        native-type="submit"
      >
        提交
      </van-button>
    </div>
  </van-form>
</template>

<script>
import { ref } from "vue";
import MyAxios from "@/plugins/MyAxios";
import router from "@/router";
import { showLoadingToast, showNotify } from "vant";

export default {
  setup() {
    let formData = new FormData();
    const username = ref("");
    const fileList = ref([]);
    const afterRead = (file) => {
      formData.append("userAvatar", file.file);
    };
    const afterDelete = (file) => {
      fileList.value = [];
      formData.delete("userAvatar");
    };

    let isSubmitting = false; // 添加一个状态标记，防止重复提交
    const onSubmit = () => {
      if (isSubmitting) return; // 添加判断，如果正在提交，则直接返回
      isSubmitting = true;

      const toast1 = showLoadingToast({
        message: "提交中...",
        forbidClick: true,
      });
      if (username.value) formData.append("userName", username.value);
      if (formData === null) return;
      MyAxios.post("/user/update/my", formData).then((res) => {
        const { code } = res;
        const { message } = res.data;
        toast1.close();
        console.log(message);
        if (code === 0) {
          showNotify({ type: "success", message: "修改成功" });
          router.push({ path: "/user" });
        } else {
          showNotify({ type: "danger", message: message });
        }
        formData = new FormData();

        isSubmitting = false; // 提交成功后，将状态置为false
      });
    };
    return {
      afterRead,
      onSubmit,
      username,
      fileList,
      afterDelete,
    };
  },
};
</script>

<style scoped></style>
